<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/7/17
 * Time: 10:51
 */
namespace app\home\controller;
use think\Db;
use think\Config;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\Controller;
class Orders extends Common
{
    /**
     * 购物车首页
     */
    public function index()
    {
        extract(input());
        $auth = $this->checkAll();
        $openid = $this->getOpenid();
        $user = Db::table('up_u_user')
            ->where('user_openid', $openid)
            ->find();
        if(!$user){
            return $this->fetch('login/login');
        }else{
            $user_id = $user['user_id'];
            if(!isset($page)){
                $page = 1;
            }
            //---------------------------------------------
            $this->updateOneToDel($user_id);
            //-----------------------------------------------
            $where = array();
            $where['order_userid'] = $user_id;
//            $where['order_in_out'] = 1;//不含退款的
            if($type > 0){
                if($type == 5){
                    $where['order_in_out'] = array('>',1);
                }else{
                    $where['order_status'] = $type;
                    $where['order_in_out'] = 1;
                }
            }
            $order = Db::table('up_order')->alias('o')
                ->join('up_shops s','o.order_shopid=s.s_id','LEFT')
                ->where($where)
                ->field('o.*,s.s_id,s.s_name,s_thumb')
                ->order('order_time DESC')
                ->page($page,10)
                ->select();
            if($order){
                foreach ($order as $k=>$v){
                    $order[$k]['goods'] = Db::table('up_order_info')
                        ->where('oi_order_id',$v['order_id'])
                        ->select();
                }
            }
            $time = time();
            $this->assign('order',$order);
            $this->assign('time',$time);
            $this->assign('type',$type);
            return $this->fetch('order/order');
        }
    }
    /**
     * 订单详情
     * order_id
     * @return string
     */
    public function myOrderInfo()
    {
        extract(input());
        $auth = $this->checkAll();
        $where = array();
        $where['order_id'] = $order_id;
        $order = Db::table('up_order')->alias('o')
            ->join('up_shops s','o.order_shopid=s.s_id','LEFT')
            ->where($where)
            ->field('o.*,s.s_id,s.s_name,s_phone,s_thumb')
            ->find();
        $goods = Db::table('up_order_info')
            ->where('oi_order_id',$order_id)
            ->select();
        $time = time();
        $this->assign('order',$order);
        $this->assign('time',$time);
        $this->assign('goods',$goods);
        $this->assign('type',$type);
        return $this->fetch('order/order_info');
    }

    /**
     * 取消订单（或者定时时间到）
     * order_id
     * @return string
     */
    public function cancelOrder()
    {
        extract(input());
        $auth = $this->checkAll();
        Db::startTrans();
        try{
            Db::table('up_order')
                ->where('order_id',$order_id)
                ->delete();
            $goods = Db::table('up_order_info')->alias('oi')
                ->join('up_goods g', 'oi.oi_good_id=g.g_id', 'LEFT')
                ->where('oi_order_id',$order_id)
                ->select();
            foreach ($goods as $k=>$v){
                //------------减库存
                if($v['g_stock'] != -1){
                    Db::table('up_goods')
                        ->where('g_id',$v['oi_good_id'])
                        ->setInc('g_stock',$v['oi_num']);
                }
                //------------------
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'取消成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 单独为取消订单做的支付
     * @return string
     */
    public function onlyPay()
    {
        extract(input());
        $openid = $this->getOpenid();
        $order = array();
        $number = date('YmdHis') . rand(1000000, 9999999);
        $order['order_number'] = $number;
        $order['order_type'] = 2;
        $order['order_where'] = 2;
        $pay = Db::table('up_order')->where('order_id', $order_id)->value('order_user_pay');
        $res = Db::table('up_order')->where('order_id', $order_id)->update($order);
        if($res){
            //===================================================================================
            $options = Config::get('wechat');
            $options['payment']['notify_url'] ='http://mww5.xuanwumobile.com/home/Car/huidiao';
            $app = new Application($options);
            $payment = $app->payment;
            //---------------------------2
            $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => "红集网",
                'detail'           => "商品购买",
                'out_trade_no'     => "$number",
                'total_fee'        => 1,//*100, // 单位：分
                'notify_url'       => 'http://mww5.xuanwumobile.com/home/Car/huidiao', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid'           => "$openid", // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                // ...
            ];
            $order = new Order($attributes);
            //--------------------------------3
            $result = $payment->prepare($order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId);
                return view('order/pay_done',['json'=>$json,'type'=>$type]);
            }else{
                return  1;
            }
        }else{
            return 2;
        }

    }
    /**
     * 确认收货
     * order_id
     * @return string
     */
    public function getMyOrder()
    {
        extract(input());
        $res = Db::table('up_order')
            ->where('order_id',$order_id)
            ->update(['order_status'=>3,'order_send_status'=>3,'order_driver_status'=>3]);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 去评价
     * order_id
     * @return string
     */
    public function goComment()
    {
        extract(input());
        $this->assign('oid',$order_id);
        $this->assign('thumb',$s_thumb);
        $this->assign('name',$s_name);
        $this->assign('type',$type);
        return $this->fetch('order/comment');
    }
    /**
     * 去投诉
     * order_id
     * @return string
     */
    public function goTousu()
    {
        extract(input());
        $this->assign('oid',$order_id);
        $this->assign('type',$type);
        return $this->fetch('order/tousu');
    }
    /**
     * 投诉订单
     * @return string
     */
    public function touSuOrder()
    {
        extract(input());
        $can = Db::table('up_order')->where('order_id',$order_id)->value('order_tousu');
        if($can == 2){
            return json(['status'=>0,'msg'=>'您已经投诉过了']);
        }
        Db::startTrans();
        try{
            Db::table('up_order')
                ->where('order_id',$order_id)
                ->update(['order_tousu'=>2,'order_tousu_reason'=>$reason]);
            //1、商户减分
            $sid = Db::table('up_order')->where('order_id',$order_id)->value('order_shopid');
            Db::table('up_shops')->where('s_id',$sid)->setDec('s_integral',5);
            $nowfen = Db::table('up_shops')->where('s_id',$sid)->value('s_integral');
            allInJifen('订单投诉：'.$reason,2,5,$sid);
            if($nowfen <= 0){
                Db::table('up_shops')->where('s_id',$sid)->update(['s_status'=>2]);
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 评价此订单
     * order_id
     * @return string
     */
    public function commentMyOrder()
    {
        extract(input());
        $have = Db::table('up_good_comment')->where('comment_order_id',$order_id)->find();
        if($have){
            return json(['status'=>0,'msg'=>'您已经评价过了']);
        }
        $auth = $this->checkAll();
        $openid = $this->getOpenid();
        $user_id = Db::table('up_u_user')
            ->where('user_openid', $openid)
            ->value('user_id');
        Db::startTrans();
        try{
            Db::table('up_order')->where('order_id',$order_id)->update(['order_status'=>4]);
            $shid = Db::table('up_order')->where('order_id',$order_id)->value('order_shopid');
            $user = Db::table('up_u_user')->where('user_id',$user_id)
                ->field('user_username,user_image')->find();
            $goodids = Db::table('up_order_info')
                ->where('oi_order_id',$order_id)
                ->column('oi_good_id');
            $str = implode($goodids,',');
            $comment = array();
            $comment['comment_goodid'] = ','.$str.',';
            $comment['comment_shopid'] = $shid;
            $comment['comment_user_id'] = $user_id;
            $comment['comment_score'] = $score;
            $comment['comment_content'] = $content;
            $comment['comment_time'] = date('Y-m-d H:i:s');
            $comment['comment_order_id'] = $order_id;
            $comment['comment_username'] = $user['user_username'];
            $comment['comment_image'] = $user['user_image'];
            Db::table('up_good_comment')->insert($comment);
            //1、商品的评分和人数修改
            foreach ($goodids as $v){
                $scoredata = Db::table('up_goods')->where('g_id',$v)->field('g_num,g_score')->find();
                $newscore = ($scoredata['g_num']*$scoredata['g_score']+$score)/($scoredata['g_num']+1);
                $goodscore = round($newscore,1);
                Db::table('up_goods')->where('g_id',$v)->update(['g_score'=>$goodscore]);
            }
            Db::table('up_goods')->where('g_id','in',$goodids)->setInc('g_num');
            //2、店铺的评分
            $shopnum = Db::table('up_good_comment')->where('comment_shopid',$shid)->count();
            $shopscore = Db::table('up_shops')->where('s_id',$shid)->value('s_score');
            $shopnewscroe = (($shopnum-1)*$shopscore+$score)/$shopnum;
            $nowscore = round($shopnewscroe,1);
            Db::table('up_shops')->where('s_id',$shid)->update(['s_score'=>$nowscore]);
            //3、评分低的话扣分
            if($score <= 3){
                //1、商户减分
                $jian_s = 4-$score;
                Db::table('up_shops')->where('s_id',$shid)->setDec('s_integral',$jian_s);
                $nowfen = Db::table('up_shops')->where('s_id',$shid)->value('s_integral');
                allInNotice('扣分通知','您有订单评价'.$score.'分，扣'.$jian_s.'分',$shid);
                allInJifen('订单评分'.$score.'分',2,$jian_s,$shid);
                if($nowfen <= 0){
                    Db::table('up_shops')->where('s_id',$shid)->update(['s_status'=>2]);
                }
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'失败']);
        }
    }
    /**
     * 申请退款
     * @return string
     */
    public function askfortuikuan()
    {
        extract(input());
        $res = Db::table('up_order')
            ->where('order_id',$order_id)
            ->update(['order_in_out'=>2]);
        if($res){
            //给商户推送
            $shop_id = Db::table('up_order')->where('order_id',$order_id)->value('order_shopid');
            try {
                sendJpush("$shop_id", '您有新的配送订单，请注意查收', array('a' => 'b'), 2, 101, 2);
            } catch(\Exception $e) {

            }
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
}